package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.cipapi.CipServiceApi;
import com.cci.kangdao.dao.CustomerEngineRelDao;
import com.cci.kangdao.dao.CustomerEngineRelLoadMsgRelationTDao;
import com.cci.kangdao.dao.CustomerEngineRelPathwayPointMapper;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.RegularLocationMapper;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.model.*;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.CustomerEngineRelLoadMsgRelationService;
import com.cci.kangdao.service.CustomerEngineRelTService;
import com.cci.kangdao.utilTool.BeanUtils;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("CustomerEngineRelLoadMsgRelationService")
public class CustomerEngineRelLoadMsgRelationImpl implements CustomerEngineRelLoadMsgRelationService {

    private Logger log = Logger.getLogger(this.getClass().getName());


    @Resource
    private CustomerEngineRelLoadMsgRelationTDao customerEngineRelLoadMsgRelationTDao;

    @Resource
    private CustomerEngineRelPathwayPointMapper customerEngineRelPathwayPointMapper;
    @Resource
    private CustomerEngineRelTService customerEngineRelTService;
    @Resource
    private CipServiceApi cipServiceApi;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Resource
    private DictionariesTDao dictionariesTDao;
    @Resource
    private RegularLocationMapper regularLocationMapper;
    @Resource
    private CustomerEngineRelDao customerEngineRelDao;

    /**
     * 提交载重信息（油耗导航）
     */
    @Override
    @Transactional
    public ModelAndView submitLoadMsg(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String paramStr = MapUtils.getString(map, "paramStr", "");
//        Map<String, Object> paramMap = JSON.parseObject(paramStr, Map.class);
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        long customerEngineRelId = MapUtils.getLongValue(map, "CustomerEngineRelId", -1);
        int carRealTotalMassType = MapUtils.getIntValue(map, "CarRealTotalMassType", -1);
        float carRealTotalMass = MapUtils.getFloatValue(map, "CarRealTotalMass", -1F);
        float carRealHeight = MapUtils.getFloatValue(map, "CarRealHeight", -1F);
        String routePreference = MapUtils.getString(map, "RoutePreference", "");
        if (customerEngineRelId == -1 || carRealTotalMassType == -1 || carRealTotalMass == -1F
                || carRealHeight == -1F || StringUtils.isBlank(routePreference)) {
            ParameterTool.writeResponse(response, 17, "缺少必要参数！");
            return null;
        }
        map.put("Creator", userT.getId());
        map.put("CreateTime", currentTime);
        customerEngineRelLoadMsgRelationTDao.insertSelective(map);
        if (map.get("PathwayPointList") != null) {
            Object pointList = com.alibaba.fastjson.JSON.toJSON(map.get("PathwayPointList"));
            List<Map> pathwayPointList = com.alibaba.fastjson.JSON.parseArray(pointList.toString(), Map.class);
//            List<Map<String,Object>> pathwayPointList =(List<Map<String,Object>>) map.get("PathwayPointList");
            if (CollectionUtils.isNotEmpty(pathwayPointList)) {
                for (Map<String, Object> stringObjectMap : pathwayPointList) {
                    stringObjectMap.put("CusEngineRelLoadId",map.get("id"));
                    stringObjectMap.put("Creator", userT.getId());
                    stringObjectMap.put("CreateTime",currentTime);
                    stringObjectMap.put("Flag",0);
                    customerEngineRelPathwayPointMapper.insertSelective(stringObjectMap);
                }
            }
        }

        Map<String, Object> mapvo = new HashMap<>();
        mapvo.put("id", map.get("id"));
        ParameterTool.writeSuccessResponse(response, mapvo);
        return null;
    }

    @Override
    public void save(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        map.put("Creator", userT.getId());
        map.put("CreateTime", currentTime);
        customerEngineRelLoadMsgRelationTDao.insertSelective(map);
    }


    @Override
    public ModelAndView getLoadMsgByCustomerEngineRelId(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        long customerEngineRelId = MapUtils.getLongValue(map, "CustomerEngineRelId", -1);
        if (customerEngineRelId == -1) {
            ParameterTool.writeResponse(response, 17, "缺少必要参数！");
            return null;
        }
        Map<String, Object> newestLoadMsg = customerEngineRelLoadMsgRelationTDao.getNewestLoadMsgByCustomerEngineRelId(customerEngineRelId);
        if (newestLoadMsg != null) {
            CustomerEngineRelLoadMsgRelationT isRecommendClass = customerEngineRelLoadMsgRelationTDao.getIsRecommendClass(userT.getId(), customerEngineRelId);
            newestLoadMsg.put("conventionalFlag", false);
            if (null != isRecommendClass) {
                newestLoadMsg.put("conventionalFlag", true);
                newestLoadMsg.put("StartingPoint", isRecommendClass.getStartingPoint());
                newestLoadMsg.put("EndPoint", isRecommendClass.getEndPoint());
                newestLoadMsg.put("StartLatitude", isRecommendClass.getStartLatitude());
                newestLoadMsg.put("StartLongitude", isRecommendClass.getStartLongitude());
                newestLoadMsg.put("EndLatitude", isRecommendClass.getEndLatitude());
                newestLoadMsg.put("EndLongitude", isRecommendClass.getEndLongitude());
            }
        }else {
            newestLoadMsg = new HashMap<>();
        }
        //查询常规地点
        CustomerEngineRelT relationByUserId = customerEngineRelDao.getCustomerEngineRelById(customerEngineRelId);
        map.put("esn",relationByUserId.getEsn());
        map.put("userId", UserThreadLocal.get().getId());
        List<RegularLocation> list = regularLocationMapper.getRegularLocationList(map);
        if (CollectionUtils.isNotEmpty(list)) {
            newestLoadMsg.put("conventionalFlag", true);
        }
        newestLoadMsg.put("RegularLocationList",CollectionUtils.isNotEmpty(list)?list:new ArrayList<>());
        ParameterTool.writeSuccessResponse(response, newestLoadMsg);
        return null;
    }

    @Override
    public BaseResponse isLoadMsgFlag(Long id) {
        CustomerEngineRelLoadMsgRelationT customerEngineRelLoadMsgRelationT = customerEngineRelLoadMsgRelationTDao.selectById(id);
        if (null == customerEngineRelLoadMsgRelationT) {
            return BaseResponse.error("请输入正确的id");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("conventionalFlag", false);
        UserT userT = UserThreadLocal.get();
        //查询常用路线  如果与常用路线一致 则不弹框
        CustomerEngineRelLoadMsgRelationT isRecommendClass = customerEngineRelLoadMsgRelationTDao.getIsRecommendClass(userT.getId(), customerEngineRelLoadMsgRelationT.getCustomerEngineRelId());
        boolean manzuFlag = false;
        if (isRecommendClass != null) {
            if(customerEngineRelLoadMsgRelationT.getStartLongitude().equals(isRecommendClass.getStartLongitude())&&
                    customerEngineRelLoadMsgRelationT.getStartLatitude().equals(isRecommendClass.getStartLatitude())&&
                    customerEngineRelLoadMsgRelationT.getEndLatitude().equals(isRecommendClass.getEndLatitude())&&
                    customerEngineRelLoadMsgRelationT.getEndLongitude().equals(isRecommendClass.getEndLongitude())){
                map.put("conventionalFlag", manzuFlag);
                return BaseResponse.success(map);
            }
        }
        List<CustomerEngineRelLoadMsgRelationT> list = customerEngineRelLoadMsgRelationTDao
                .getListByCusEngineIdAnduserId(userT.getId()
                        , customerEngineRelLoadMsgRelationT.getCustomerEngineRelId());
        if (CollectionUtils.isNotEmpty(list)) {
            if (list.size() >= 3) {
                manzuFlag = list.subList(0, 3).stream().allMatch(
                            e -> e.getStartLatitude().equals(customerEngineRelLoadMsgRelationT.getStartLatitude())
                                    && e.getStartLongitude().equals(customerEngineRelLoadMsgRelationT.getStartLongitude())
                                    && e.getEndLatitude().equals(customerEngineRelLoadMsgRelationT.getEndLatitude())
                                    && e.getEndLongitude().equals(customerEngineRelLoadMsgRelationT.getEndLongitude())
                    );

                    map.put("conventionalFlag", manzuFlag);
                }
            }
        return BaseResponse.success(map);
    }

    @Override
    @Transactional
    public BaseResponse updateLoadMsgNum(Long id) {
        CustomerEngineRelLoadMsgRelationT customerEngineRelLoadMsgRelationT = customerEngineRelLoadMsgRelationTDao.selectById(id);
        if (null == customerEngineRelLoadMsgRelationT) {
            return BaseResponse.error("请输入正确的id");
        }
        UserT userT = UserThreadLocal.get();
        //先将已经存在的删除，然后添加
        CustomerEngineRelLoadMsgRelationT isRecommendClass = customerEngineRelLoadMsgRelationTDao.getIsRecommendClass(userT.getId(), customerEngineRelLoadMsgRelationT.getCustomerEngineRelId());
        if (null != isRecommendClass) {
            isRecommendClass.setUpdator(userT.getId());
            isRecommendClass.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            isRecommendClass.setFlag(-1);
            int updateNum = customerEngineRelLoadMsgRelationTDao.updateByPrimaryKeySelective(isRecommendClass);
        }
        CustomerEngineRelLoadMsgRelationT updatecustomer = new CustomerEngineRelLoadMsgRelationT();
        updatecustomer.setID(customerEngineRelLoadMsgRelationT.getID());
        updatecustomer.setIsRecommend(1);
        updatecustomer.setUpdator(userT.getId());
        updatecustomer.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
        int updateNum = customerEngineRelLoadMsgRelationTDao.updateByPrimaryKeySelective(updatecustomer);
        List<RegularLocation> list = regularLocationMapper.selectByCustormerId(customerEngineRelLoadMsgRelationT.getCustomerEngineRelId());
        if (CollectionUtils.isNotEmpty(list)) {
            if (list.size()>=5) {
                RegularLocation regularLocation = list.get(0);
                regularLocation.setFlag(-1);
                regularLocation.setDeleter(userT.getId());
                regularLocation.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
                regularLocationMapper.updateByPrimaryKey(regularLocation);
            }
            RegularLocation regularLocation = new RegularLocation();
            regularLocation.setUserId(userT.getId());
            regularLocation.setEndPoint(customerEngineRelLoadMsgRelationT.getEndPoint());
            regularLocation.setEndLongitude(customerEngineRelLoadMsgRelationT.getEndLongitude());
            regularLocation.setEndLatitude(customerEngineRelLoadMsgRelationT.getEndLatitude());
            CustomerEngineRelT customerEngineRelById = customerEngineRelDao.getCustomerEngineRelById(customerEngineRelLoadMsgRelationT.getCustomerEngineRelId());
            regularLocation.setESN(customerEngineRelById.getEsn());
            regularLocation.setCustomerEngineId(customerEngineRelLoadMsgRelationT.getCustomerEngineRelId());
            regularLocation.setFlag(0);
            regularLocation.setCreator(userT.getId());
            regularLocation.setCreateTime(LocalTimeUtil.getRealCurrentTime());
            regularLocationMapper.insertSelective(regularLocation);
        }
        return BaseResponse.success(updateNum > 0);
    }

    @Override
    public int getIsRecommend(Long customerEngineRelId) {
        UserT userT = UserThreadLocal.get();
        return customerEngineRelLoadMsgRelationTDao.getIsRecommend(userT.getId()
                , customerEngineRelId);
    }

    @Override
    public CustomerEngineRelLoadMsgRelationT getIsRecommendClass(Long customerEngineRelId) {
        UserT userT = UserThreadLocal.get();
        return customerEngineRelLoadMsgRelationTDao.getIsRecommendClass(userT.getId()
                , customerEngineRelId);
    }

    @Override
    public int update(CustomerEngineRelLoadMsgRelationT customerEngineRelLoadMsgRelationT) {
        return customerEngineRelLoadMsgRelationTDao.updateByPrimaryKeySelective(customerEngineRelLoadMsgRelationT);
    }

    @Override
    public BaseResponse updateLoadMsgComments(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        map.put("Updator", userT.getId());
        map.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
        int update = customerEngineRelLoadMsgRelationTDao.updateLoadMsgComments(map);
        if (update > 0) {
            return BaseResponse.success("更新成功");
        } else {
            return BaseResponse.error(-99, "更新失败");
        }
    }

    /**
     * 提交油耗导航行程数据记录（油耗导航）
     * @param paramStr
     * @return
     */
    @Override
    public boolean submitFuelTrip(String paramStr) {
        UserT userT = UserThreadLocal.get();
        int i = 0;
         // 加锁处理，避免发生多次提交。
        String lockKey= "submitFuelTrip-" + userT.getId();
        if (!redisClientUtils.lock(lockKey, 60L)) {
           return false;
        }
        try {
            submitFuelTripInfo info = JSON.parseObject(paramStr, submitFuelTripInfo.class);
            if(null != info.getLoadMsgId()){
                FuelBehaviorRecommedInfo fuelInfo = customerEngineRelLoadMsgRelationTDao.getFuelTripRecommedByLoadMsgId(info.getLoadMsgId());
                if(null == fuelInfo){
                    FuelTripRecordT fuelTripRecordT = BeanUtils.convert(info, FuelTripRecordT.class);
                    fuelTripRecordT.setUserId(userT.getId());
                    fuelTripRecordT.setCreator(userT.getId());
                    fuelTripRecordT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    i = customerEngineRelLoadMsgRelationTDao.insertFuelTrip(fuelTripRecordT);
                    if(i > 0){
                        double totalDistanceMin = 50;
                        String totalDistanceStr = dictionariesTDao.getListByDTableNameAndDInt("tTotalDistance","0");
                        if(StringUtils.isNotBlank(totalDistanceStr)){
                            totalDistanceMin = Double.valueOf(totalDistanceStr);
                        }
                        if(Double.valueOf(info.getTotalDistance()) >= totalDistanceMin && Double.valueOf(info.getTotalFuel()) > 0){
                            //添加 是否请求  cip的状态  包含 此判断和历史的数据
                            FuelTripRecordT fuelTripRecordTUpdte = new FuelTripRecordT();
                            fuelTripRecordTUpdte.setId(fuelTripRecordT.getId());
                            fuelTripRecordTUpdte.setRequestType(1);
                            customerEngineRelLoadMsgRelationTDao.updateFuelTripById(fuelTripRecordTUpdte);
                            //同步油耗驾驶行为建议信息
                            FuelBehaviorRecommedInfo recommedInfo = customerEngineRelLoadMsgRelationTDao.getFuelTripRecommedByLoadMsgId(info.getLoadMsgId());
                            cipServiceApi.syncFuelBehaviorRecommed(recommedInfo);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }finally {
            //释放锁
            redisClientUtils.delkey(lockKey);
        }
        return i > 0;
    }

    /**
     * 现行故障码
     * @param esn
     * @return
     */
    @Override
    public List<CurrentFaultsInfo> getCurrentFaultsbyEsn(String esn, String startTime) {
        List<CurrentFaultsInfo> list = customerEngineRelLoadMsgRelationTDao.getCurrentFaultsbyEsn(esn,startTime);
        return list;
    }

    /**
     * 获取 增加历史行程记录
     * @param map
     * @return
     */
    @Override
    public BaseResponse getLoadMsgSearch(Map<String, Object> map) {
        map.put("userId",UserThreadLocal.get().getId());
        return BaseResponse.success(customerEngineRelLoadMsgRelationTDao.getLoadMsgSearch(map));
    }

    @Override
    public ModelAndView getLoadMsgHistory(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        Integer page = MapUtils.getInteger(map, "page", 1);
        Integer pageSize = MapUtils.getInteger(map, "pageSize", 10);
        map.put("userId",UserThreadLocal.get().getId());
        if (null==MapUtils.getLong(map,"customerEngineRelId")) {
            map.remove("customerEngineRelId");
        }
        if (StringUtils.isBlank(MapUtils.getString(map,"esn"))) {
            map.remove("esn");
        }
        PageHelper.startPage(page,pageSize);
        PageHelper.orderBy("  cerlmrt.ID DESC");
        List<Map<String,Object>> loadMsgHistory = customerEngineRelLoadMsgRelationTDao.getLoadMsgHistory(map);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(loadMsgHistory);
        ParameterTool.writeSuccessResponse(response, pageInfo);
        return null;
    }

    /**
     * 提交油耗导航行程数据记录（油耗导航）
     * @param info
     * @return
     */
    @Override
    public boolean updateFuelTrip(FuelTripRecordInfo info) {
        FuelTripRecordT fuelTripRecordT = BeanUtils.convert(info, FuelTripRecordT.class);
        fuelTripRecordT.setUpdator(info.getUserId());
        fuelTripRecordT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
        int i = customerEngineRelLoadMsgRelationTDao.updateFuelTrip(fuelTripRecordT);
        return i > 0;
    }

    /**
     * 更新油耗导航驾驶行为建议
     * @param info
     * @return
     */
    @Override
    public boolean updateFuelTripSuggest(FuelTripRecordInfo info) {
        boolean success = false;
        FuelTripRecordInfo fuelTripRecordInfo = customerEngineRelLoadMsgRelationTDao.getFuelTripRecordByLoadMsgId(info.getLoadMsgId());
        if(null != fuelTripRecordInfo && null != fuelTripRecordInfo.getUserId()){
            info.setUserId(fuelTripRecordInfo.getUserId());
            success = updateFuelTrip(info);
            if(info.getSuggestType() == 1){
                String createTime = fuelTripRecordInfo.getCreateTime();
                String time = createTime.substring(0,4) + "年" + createTime.substring(5,7) + "月" + createTime.substring(8,10) + "日" + createTime.substring(11,13) + "时";
                String content = "您的车辆" + fuelTripRecordInfo.getPlateNumber() + "于" + time + "的历史行程驾驶行为分析报告已出，快来查看！";
                PublicSendNotifyRequest request = new PublicSendNotifyRequest();
                List<Long> userIdList = new ArrayList<>();
                userIdList.add(fuelTripRecordInfo.getUserId());
                request.setUserIdList(userIdList);
                request.setContent(content);
                request.setActionCode("monthlyReport");
                Map<String,Object> paramsMap = new HashMap<>();
                paramsMap.put("esn",fuelTripRecordInfo.getEsn());
                paramsMap.put("loadMsgId",info.getLoadMsgId());
                String params = JSONArray.toJSON(paramsMap).toString();
                customerEngineRelTService.FuelTripReportPush(request,fuelTripRecordInfo.getUserName(),params);
            }
        }
        return success;
    }

    @Override
    public FuelTripRecordInfo getFuelTripById(Long id) {
        FuelTripRecordInfo info = customerEngineRelLoadMsgRelationTDao.getFuelTripRecordByLoadMsgId(id);
        return info;
    }

}
